// Copyright NaChuanSoftware Author(https://github.com/LiuShuKu). All Rights Reserved.

// Copyright (c)  2023 LiuShuKu
// Project Name :   balance
// Author       :   liushuku@yeah.net

// Package tron .
package tron

import (
	"context"
	"encoding/hex"
	"fmt"
	"github.com/fbsobreira/gotron-sdk/pkg/client"
	"github.com/gogf/gf/v2/os/glog"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"strings"
	"time"
)

const (
	// TRON 波场地址
	tronGrpcLink = "grpc.trongrid.io:50051"
	// GRPC 超时时间
	grpcConnectTimeout = 30 * time.Second
)

type tronGrpcs struct {
	node string
	grpc *client.GrpcClient
}

var tronGrpc = &tronGrpcs{}

// connect 链接波场
func (t *tronGrpcs) connect(ctx context.Context) (grpcClient *tronGrpcs, err error) {
	{
		// 指定波场
		t.node = tronGrpcLink
		// 链接波场
		t.grpc = client.NewGrpcClientWithTimeout(tronGrpcLink, grpcConnectTimeout)
		// 启动服务
		if err = t.grpc.Start(grpc.WithTransportCredentials(insecure.NewCredentials())); err != nil {
			glog.Errorf(ctx, "链接波场失败: %s ", err.Error())
			return
		}
		// 返回
		grpcClient = t
	}
	return
}

// keepConnect 检测连接
func (t *tronGrpcs) keepConnect() error {
	_, err := t.grpc.GetNodeInfo()
	if err != nil {
		if strings.Contains(err.Error(), "no such host") {
			return t.grpc.Reconnect(t.node)
		}
		return fmt.Errorf("url connect error: %v", err)
	}
	return nil
}

// stop 结束连接
func (t *tronGrpcs) stop() {
	if t != nil && t.grpc != nil {
		t.grpc.Stop()
	}
}

// bytesToHexString 交易bytes 转 16进制 字符串
func bytesToHexString(bytes []byte) string {
	encode := make([]byte, len(bytes)*2)
	hex.Encode(encode, bytes)
	return string(encode)
}
